#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using TVC.Layout;
using System.Xml;
using System.IO;
using System.Data.SqlClient;
using System.Data.Common;

#endregion

namespace TVC.Modules.Ref
{
    public partial class Budget : ModuleParent, IHostedApplication
    {
        int idAllowEditLanguage = 1;
        int idAddNew = 188;
        int idEdit = 189;
        int idDelete = 190;
        int idTransferIn = 191;
        int idPrint = 192;
        int idShare = 193;
        int idToExcel = 266;

        bool _isCalculate = true;
        string strAction = "";
        bool bllNew = true;
        //DataTable dtbBudget = null;

        public Budget()
        {
            InitializeComponent();
            _dgvFilter = gridFilter1;
            _dgvList = dgvBudget;
            _strType = "Budget";


        }



        public void InitializeApplication()
        {
        }

        public void SetObject(object obj)
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));

            objElements.Add(new HostedToolBarSeperator()); if (IsPermis(idTransferIn)) objElements.Add(new HostedToolBarButton("Import", "Import", new IconResourceHandle("Down.png"), "TI", false));
            //if (IsPermis(idTransferOut))
            //    objElements.Add(new HostedToolBarButton("Transfer Out", new IconResourceHandle("Up.png"), "TO"));
            //objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idPrint)) objElements.Add(new HostedToolBarButton("To XML", "To XML", new IconResourceHandle("Up.png"), "TO", false));
            if (IsPermis(idToExcel)) objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Excel.png"), "TX", false));
            //if (IsPermis(idShare)) objElements.Add(new HostedToolBarButton("Share budget reference check", "Share budget reference check", new IconResourceHandle("Class.gif"), "P"));
            //objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }


        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            try
            {
                sErr = "";
                strAction = (string)objButton.Tag;

                BUS.BudgetsControl ctr = new BUS.BudgetsControl();
                switch (strAction)
                {
                    case "C"://add
                        AddNew(txtBudgetCode);
                        break;
                    case "A":// edit
                        editRecord(txtBudgetCode);

                        break;
                    case "S":// save
                        saveRecord(txtBudgetCode);

                        break;
                    case "O"://copy
                        copy(txtBudgetCode);
                        break;
                    case "X": //Delete
                        delete(txtBudgetCode);

                        break;
                    case "K":
                        skip();
                        break;
                    case "TI": //trans in
                        importData();
                        break;
                    case "TO": //Tran out
                        export2Xml();
                        break;
                    case "TX": //Tran out
                        export2Excel();
                        break;
                    //case "R":
                    //    RefreshList();
                    //    break;
                    case "P": //
                        if (dgvBudget.CurrentCell != null)
                        {
                            //DTO.OrganizationsInfo info = new DTO.OrganizationsInfo((DataRowView)dgvList.CurrentRow.DataBoundItem);
                            //DataTable dt = DTO.OrganizationsInfo.ToDataTable();
                            //dt.Rows.Add(info.ToDataRow(dt));
                            //DataSet ds = new DataSet();
                            //ds.Tables.Add(dt);
                            //MainForm main = GetMainForm();
                            //if (main != null)
                            //    main.PrintDataSet(ds, _strType);
                        }
                        break;
                }
                if (sErr == "") ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            }
        }


        #region .::| Override Functions |::.
        protected override ErrorStatus validateForm(ref string sErr)
        {
            ErrorStatus result = ErrorStatus.SUCCESS;
            errorPro.SetError(txtBudgetCode, "");
            errorPro.SetError(chkUncheckI, "");

            BUS.BudgetsControl ctr = new BUS.BudgetsControl();

            if (txtBudgetCode.Text.Trim() == "")
            {
                sErr += "Could not save blank Budget, please check!\n";
                errorPro.SetError(txtBudgetCode, "Could not save blank Budget, please check!");
                txtBudgetCode.Focus();
                //return;
            }

            if (!string.IsNullOrEmpty(cboSunBg.Text) && cboSunBg.Value == "")
            {
                sErr += "Sun Budget is not in list, please check!\n";
                errorPro.SetError(cboSunBg, "Sun Budget is not in list!");
                cboSunBg.Focus();
            }

            //if (cboBudgetG.Text.Trim() != "" && string.Format("{0}", cboBudgetG.SelectedValue) == "")
            //{
            //    sErr += "Budget Group is not in list, please check!\n";
            //    errorPro.SetError(cboSunBg, "Budget Group is not in list!");
            //    strAction = _processStatus;
            //    cboBudgetG.Focus();
            //}

            DTO.BudgetsInfo info = GetData();
            if (ctr.IsExistGroupOtherShared(GetMainForm().PODInfo.Business_ID, info.Contract, info.aYear, info.BudgetGroup, info.SharedBudget))
            {
                sErr += "There are shared budget and none shared budget in budget group " + info.BudgetGroup + ", please check!\n";
                errorPro.SetError(chkUncheckI, "There are shared budget and none shared budget in budget group " + info.BudgetGroup + ", please check!");
                strAction = _processStatus;
                chkUncheckI.Focus();
            }

            if (sErr != "") result = ErrorStatus.ERROR;

            return result;
        }
        protected override bool checkExists()
        {
            BUS.BudgetsControl ctr = new BUS.BudgetsControl();
            return ctr.IsExist(GetMainForm().PODInfo.Business_ID, txtBudgetCode.Text, Convert.ToInt32(txtBudgetYear.Value));
        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.BudgetsControl ctr = new BUS.BudgetsControl();
            DTO.BudgetsInfo info = GetData();

            object trans = ctr.BeginTransaction(ref sErr);
            if (sErr == "") ctr.Add(GetMainForm().PODInfo.Business_ID, info, ref sErr);

            if (sErr == "") sErr = ctr.Update_Shared(info);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }
        protected override string updateRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.BudgetsControl ctr = new BUS.BudgetsControl();
            DTO.BudgetsInfo info = GetData();
            object trans = ctr.BeginTransaction(ref sErr);
            if (sErr == "") sErr = ctr.Update(GetMainForm().PODInfo.Business_ID, info);
            if (sErr == "") sErr = ctr.Update_Shared(info);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }

        protected override string delRecord()
        {
            BUS.BudgetsControl ctr = new BUS.BudgetsControl();

            return ctr.Delete(GetMainForm().PODInfo.Business_ID, txtBudgetCode.Text, Convert.ToInt32(txtBudgetYear.Value));

        }

        protected override void refreshForm(string str)
        {
            _isCalculate = false;
            gbPrimary.SuspendLayout();
            txtBudgetCode.Text = "";
            txtBudgetYear.Value = DateTime.Today.Year;
            //cboBudgetGroup.Text = "";
            cboBudgetG.SelectedValue = "";
            cboSunBg.Value = "";
            txtTotalLimitAmt.Value = 0;
            txtTotalRequisition.Value = 0;
            txtDecription.Text = "";
            txtRemaining.Value = 0;
            chkUncheckI.Checked = false;
            txtValue1.Value = 0;
            txtDate1.Text = "";
            txtNote11.Text = "";
            txtNote21.Text = "";
            txtValue2.Value = 0;
            txtDate2.Text = "";
            txtNote12.Text = "";
            txtNote22.Text = "";
            txtValue3.Value = 0;
            txtDate3.Text = "";
            txtNote13.Text = "";
            txtNote23.Text = "";
            txtValue4.Value = 0;
            txtDate4.Text = "";
            txtNote14.Text = "";
            txtNote24.Text = "";
            txtValue5.Value = 0;
            txtDate5.Text = "";
            txtNote15.Text = "";
            txtNote25.Text = "";
            txtBudgetHolder.Text = "";
            txtDepartment.Text = "";
            txtEmployee.Text = "";
            gbPrimary.ResumeLayout(true);
            _isCalculate = true;
        }
        protected override void enableForm(bool val)
        {
            gbPrimary.SuspendLayout();
            txtBudgetCode.Enabled = val;
            txtBudgetYear.Enabled = val;
            //cboBudgetGroup.Enabled = val;
            cboBudgetG.Enabled = val;
            cboSunBg.Enabled = val;
            txtTotalLimitAmt.Enabled = val;
            //txtTotalRequisition.Enabled = val;
            txtDecription.Enabled = val;
            //txtRemaining.Enabled = val;
            chkUncheckI.Enabled = val;
            txtValue1.Enabled = val;
            txtDate1.Enabled = val;
            txtNote11.Enabled = val;
            txtNote21.Enabled = val;
            txtValue2.Enabled = val;
            txtDate2.Enabled = val;
            txtNote12.Enabled = val;
            txtNote22.Enabled = val;
            txtValue3.Enabled = val;
            txtDate3.Enabled = val;
            txtNote13.Enabled = val;
            txtNote23.Enabled = val;
            txtValue4.Enabled = val;
            txtDate4.Enabled = val;
            txtNote14.Enabled = val;
            txtNote24.Enabled = val;
            txtValue5.Enabled = val;
            txtDate5.Enabled = val;
            txtNote15.Enabled = val;
            txtNote25.Enabled = val;
            txtBudgetHolder.Enabled = val;
            txtDepartment.Enabled = val;
            txtEmployee.Enabled = val;

            if (val == false)
            {
                foreach (Control x in gbPrimary.Controls)
                {
                    if (errProvider.GetError(x) != string.Empty) errProvider.SetError(x, "");
                }
            }
            gbPrimary.ResumeLayout(true);
        }

        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.BudgetsInfo inf = new DTO.BudgetsInfo((DataRowView)o);
                SetData(inf);
            }
        }

        #endregion




        private void LoadMultiCombo()
        {
            // Organizations
            BUS.BudgetsControl ctrcontr = new BUS.BudgetsControl();
            DataTable dtbgG = ctrcontr.GetGroup(GetMainForm().PODInfo.Business_ID, ref sErr);
            /*GridLayout layoutCus = new GridLayout(MainForm.ServerPath
                + "Resources\\Layout\\", MainForm.ServerPath + "Documents\\Layout\\"
                + GetMainForm().PODInfo.USER_ID + "\\", "bgGroup");
            GetMainForm().InitMultiComboBox(cboBudgetGroup, layoutCus, DTO.BudgetsInfo.Field.BudgetGroup.ToString(), DTO.BudgetsInfo.Field.BudgetGroup.ToString());
            cboBudgetGroup.Binding = dtbgG;*/
           
            cboBudgetG.DataSource = dtbgG;
            cboBudgetG.DisplayMember = "BudgetGroup";
            cboBudgetG.ValueMember = "BudgetGroup";

            BUS.SSRFANVControl ctrOrgan = new BUS.SSRFANVControl();

            DataTable dtExpC = new DataTable();
            dtExpC = ctrOrgan.GetAll_SSRFANVBU("T2", GetMainForm().SUNDB, ref sErr, MainForm.HLConnect);
            cboSunBg.MainForm = GetMainForm();
            cboSunBg.DisplayMember = "CODE";
            cboSunBg.ValueMember = "CODE";
            cboSunBg.Lookup = "SSRFANV";
            cboSunBg.DataSource = dtExpC;

            ///////////

        }

        private void Budget_Load(object sender, EventArgs e)
        {
            LoadMultiCombo();
            txtBudgetYear.Value = DateTime.Now.Year;
            refreshForm("");
            enableForm(false);
        }

        private void gridFilter1_GridFiterEvent(string strFilter, int year)// filter
        {
            string sErr = "";
            BUS.BudgetsControl ctrBud = new BUS.BudgetsControl();
            FormatDate();
            DataTable dtb = ctrBud.GetCond(GetMainForm().PODInfo.Business_ID, strFilter, ref sErr);
            if (!string.IsNullOrEmpty(gridFilter1.SortField))
            {
                dtb.DefaultView.Sort = gridFilter1.SortField + " " + gridFilter1.Direction;
            }
            bisBudget.DataSource = dtb;

            double sLimit = 0;
            double sReq = 0;
            double sRem = 0;
            double sV1 = 0;
            double sV2 = 0;
            double sV3 = 0;
            double sV4 = 0;
            double sV5 = 0;

            double temp;
            foreach (DataRow row in dtb.Rows)
            {

                sLimit += double.TryParse(row["LimitAmt"].ToString(), out temp) ? (double)row["LimitAmt"] : 0;
                sReq += double.TryParse(row["Requisition"].ToString(), out temp) ? (double)row["Requisition"] : 0;
                sRem += double.TryParse(row["Remaining"].ToString(), out temp) ? (double)row["Remaining"] : 0;
                sV1 += double.TryParse(row["ValueV1"].ToString(), out temp) ? (double)row["ValueV1"] : 0;
                sV2 += double.TryParse(row["ValueV2"].ToString(), out temp) ? (double)row["ValueV2"] : 0;
                sV3 += double.TryParse(row["ValueV3"].ToString(), out temp) ? (double)row["ValueV3"] : 0;
                sV4 += double.TryParse(row["ValueV4"].ToString(), out temp) ? (double)row["ValueV4"] : 0;
                sV5 += double.TryParse(row["ValueV5"].ToString(), out temp) ? (double)row["ValueV5"] : 0;
            }

            txtLimit.Value = (decimal)sLimit;
            txtRequisition.Value = (decimal)sReq;
            txtRemainingAtm.Value = (decimal)sRem;
            txtValueV1.Value = (decimal)sV1;
            txtValueV2.Value = (decimal)sV2;
            TxtValueV3.Value = (decimal)sV3;
            txtValueV4.Value = (decimal)sV4;
            txtValueV5.Value = (decimal)sV5;



        }





        private void calTotal()
        {
            decimal totallimit = 0;
            totallimit = decimal.Parse(txtValue1.Value.ToString()) +
                decimal.Parse(txtValue2.Value.ToString()) +
                decimal.Parse(txtValue3.Value.ToString()) +
                decimal.Parse(txtValue4.Value.ToString()) +
                decimal.Parse(txtValue5.Value.ToString());

            txtTotalLimitAmt.Value = totallimit;

            BUS.BudgetsControl ctr = new BUS.BudgetsControl();

            decimal dcmTotalRequisition = ctr.getSumAmt(GetMainForm().PODInfo.Business_ID, txtBudgetCode.Text, Convert.ToInt32(txtBudgetYear.Value), ref sErr);

            txtTotalRequisition.Value = dcmTotalRequisition;
            txtRemaining.Value = txtTotalLimitAmt.Value - txtTotalRequisition.Value;
        }

        private DTO.BudgetsInfo GetData()
        {
            double totallimit = 0;
            totallimit = double.Parse(txtValue1.Value.ToString()) +
                double.Parse(txtValue2.Value.ToString()) +
                double.Parse(txtValue3.Value.ToString()) +
                double.Parse(txtValue4.Value.ToString()) +
                double.Parse(txtValue5.Value.ToString());

            txtTotalLimitAmt.Value = Convert.ToDecimal(totallimit);
            txtRemaining.Value = txtTotalLimitAmt.Value - txtTotalRequisition.Value;

            return new DTO.BudgetsInfo(
                txtBudgetCode.Text,
                totallimit,//double.Parse(txtTotalLimitAmt.Value.ToString()),
                0,
                double.Parse(txtTotalRequisition.Value.ToString()),
                double.Parse(txtRemaining.Value.ToString()),
                txtBudgetHolder.Text,
                txtDecription.Text,
                double.Parse(txtValue1.Value.ToString()),
                double.Parse(txtValue2.Value.ToString()),
                double.Parse(txtValue3.Value.ToString()),
                double.Parse(txtValue4.Value.ToString()),
                double.Parse(txtValue5.Value.ToString()),
                txtNote11.Text,
                txtNote12.Text,
                txtNote13.Text,
                txtNote14.Text,
                txtNote15.Text,
                txtNote21.Text,
                txtNote22.Text,
                txtNote23.Text,
                txtNote24.Text,
                txtNote25.Text,
                txtDate1.Value,
                txtDate2.Value,
                txtDate3.Value,
                txtDate4.Value,
                txtDate5.Value,
               Convert.ToInt32(txtBudgetYear.Value),
                cboBudgetG.Text.Trim(),
                txtDepartment.Text,
                txtEmployee.Text,
                short.Parse(chkUncheckI.Checked ? "1" : "0"),
                "",
                int.Parse(DateTime.Today.ToString("yyyyMMdd")),
                int.Parse(DateTime.Today.ToString("yyyyMMdd")),
                "",
                0,
                GetMainForm().PODInfo.USER_ID,
                GetMainForm().PODInfo.USER_ID,
                cboSunBg.Value.ToString()
                );

        }

        private void SetData(DTO.BudgetsInfo info)
        {
            txtBudgetCode.Text = info.Contract;
            txtBudgetYear.Value = info.aYear;
            cboBudgetG.Text = info.BudgetGroup;
            //cboBudgetG.SelectedValue = info.BudgetGroup;
            txtTotalLimitAmt.Value = decimal.Parse(info.LimitAmt.ToString());
            txtTotalRequisition.Value = decimal.Parse(info.CummulativeAmt.ToString());
            txtDecription.Text = info.Desc;
            txtRemaining.Value = decimal.Parse(info.RemainingAmt.ToString());
            chkUncheckI.Checked = bool.Parse(info.SharedBudget.ToString() == "1" ? "true" : "false");
            txtValue1.Value = decimal.Parse(info.LimitAmtV1.ToString());
            txtDate1.Text = (info.Date1 == DateTime.MinValue ? "" : info.Date1.ToString("dd/MM/yyyy"));
            txtNote11.Text = info.Desc1V1;
            txtNote21.Text = info.Desc2V1;
            txtValue2.Value = decimal.Parse(info.LimitAmtV2.ToString());
            txtDate2.Text = (info.Date2 == DateTime.MinValue ? "" : info.Date2.ToString("dd/MM/yyyy"));
            txtNote12.Text = info.Desc1V2;
            txtNote22.Text = info.Desc2V2;
            txtValue3.Value = decimal.Parse(info.LimitAmtV3.ToString());
            txtDate3.Text = (info.Date3 == DateTime.MinValue ? "" : info.Date3.ToString("dd/MM/yyyy"));
            txtNote13.Text = info.Desc1V3;
            txtNote23.Text = info.Desc2V3;
            txtValue4.Value = decimal.Parse(info.LimitAmtV4.ToString());
            txtDate4.Text = (info.Date4 == DateTime.MinValue ? "" : info.Date4.ToString("dd/MM/yyyy"));
            txtNote14.Text = info.Desc1V4;
            txtNote24.Text = info.Desc2V4;
            txtValue5.Value = decimal.Parse(info.LimitAmtV5.ToString());
            txtDate5.Text = (info.Date5 == DateTime.MinValue ? "" : info.Date5.ToString("dd/MM/yyyy"));
            txtNote15.Text = info.Desc1V5;
            txtNote25.Text = info.Desc2V5;
            txtBudgetHolder.Text = info.ContractHolder;
            txtDepartment.Text = info.Department;
            txtEmployee.Text = info.Employee;
            cboSunBg.Value = info.Group1;
        }

        private void txt_DoubleClick(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;
            MessageBox.Show(txt.Text, "Full text");
        }

        private void cboBudgetGroup_ComboText_Changed(object sender, CustomControl.MultiColumnCombo.ComboChangedEventArgs e)
        {
            //cboBudgetG.SelectedValue = cboBudgetGroup.RowData["BudgetGroup"].ToString().Trim();
        }

        private void txtTotalLimitAmt_Enter(object sender, EventArgs e)
        {
            (sender as NumericUpDown).Select(0, (sender as NumericUpDown).ToString().Length);
        }

        private void cboBudgetG_Leave(object sender, EventArgs e)
        {
            //if (cboBudgetG.Text != null && cboBudgetG.Text.Trim() != "")
            //{
            //    if (cboBudgetG.SelectedValue == null)
            //    {
            //        cboBudgetG.Focus();
            //        MessageBox.Show(" Please select from the list ", false);
            //    }
            //}
        }

        private void cboSunBg_Leave(object sender, EventArgs e)
        {
            if (cboSunBg.Text != null && cboSunBg.Text.Trim() != "")
            {
                if (cboSunBg.Value.ToString() == "")
                {
                    cboSunBg.Focus();
                    MessageBox.Show(" Please select from the list ", false);
                }
            }
        }


    }
}